package io.wins.vertx.verticle.api;

import io.vertx.core.Future;
import io.vertx.core.eventbus.Message;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.wins.vertx.entity.User;
import io.wins.vertx.service.UserService;
import io.wins.vertx.utils.EncryptUtils;

public class UserApiVerticle extends RestApiVerticle {

    public static final String USER_REST_ADDRESS = "io.wins.rest.user#%1$s";
    public static final String REGISTER_USER = "register";
    public static final String LOGIN_USER = "loginUser";
    public static final String LIST_USER = "listUser";
    public static final String CHECK_ID = "checkId";
    private static final Logger logger = LoggerFactory.getLogger(UserApiVerticle.class);

    private final UserService service;

    public UserApiVerticle(final UserService service) {
        this.service = service;
    }

    @Override
    public void start(final Future<Void> startFuture) throws Exception {
        this.on(String.format(USER_REST_ADDRESS, REGISTER_USER), this::registerUser);
        this.on(String.format(USER_REST_ADDRESS, CHECK_ID), this::checkId);
        this.on(String.format(USER_REST_ADDRESS, LOGIN_USER), this::loginUser);
        this.on(String.format(USER_REST_ADDRESS, LIST_USER), this::listUser);
//        final Router router = SingletonRouter.getInstance().getRouter();
//        router.post("/api/user/:id").handler(this::getUser);
        startFuture.complete();
    }

    private void checkId(final Message<JsonObject> tMessage) {
        final JsonObject param = tMessage.body().getJsonObject("param");
        final String loginId = param.getString("loginId");
        this.service.checkLoginId(loginId, tMessage);
    }

    private void listUser(final Message<JsonObject> tMessage) {
        this.service.listUser(tMessage);
    }

    private void registerUser(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body");
        final User user = new User(body.getJsonObject("registerData"));
        user.setSalt(EncryptUtils.genSalt());
        user.setPassword(EncryptUtils.encrypt(user.getPassword(), user.getSalt()));
        this.service.registerUser(user, tMessage);
    }

    private void loginUser(final Message<JsonObject> tMessage) {
        final JsonObject body = tMessage.body().getJsonObject("body");
        final String loginId = body.getString("loginId");
        final String password = body.getString("password");
        final int key = body.getInteger("key", 0);
        this.service.getUserByLoginId(loginId, password, key, tMessage);
    }
}
